﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.WindowsLive.Id.Client;
using System.Diagnostics;

namespace Microsoft.Forums.MicrosoftForumsProvider
{
    public static class PassportHelper
    {
        private static IdentityManager identityManager;
        private static Identity identity;
        private static readonly string SERVICENAME = "microsoft.com";

        /// <summary>
        /// Gets or sets the authorization ticket.
        /// </summary>
        /// <value>The auth ticket.</value>
        public static string AuthTicket
        {
            get;
            set;
        }

        /// <summary>
        /// Authenticates the user.
        /// </summary>
        /// <returns></returns>
        public static string AuthenticateUser()
        {
            try
            {
                if (identity.IsAuthenticated || identity.Authenticate())
                {
                    AuthTicket = identity.GetTicket(SERVICENAME, true);
                    return identity.UserName;
                }
            }
            catch (WLLogOnException wlex)
            {
                //Check to see if FlowUrl is defined.
                if (wlex.FlowUrl != null)
                {
                    //If FlowUrl is defined, direct user to the web page to correct the error.
                    Debug.WriteLine(wlex.ErrorString + "Please go to " + wlex.FlowUrl.AbsoluteUri + "to correct the condition that caused the error");
                }
                else
                {
                    //If FlowUrl is not defined, simply display the ErrorString.
                   Debug.WriteLine(wlex.ErrorString);
                }
            }
            throw new ApplicationException("Authentication Failed");
        }

        /// <summary>
        /// Initializes the <see cref="PassportHelper"/> class.
        /// </summary>
        static PassportHelper()
        {
            try
            {
                identityManager = IdentityManager.CreateInstance(Properties.Resources.LiveIdInformationString, Properties.Resources.LiveIdTitleString);
                identity = identityManager.CreateIdentity();
            }
            catch (WLLogOnException wlex)
            {
                //Check to see if FlowUrl is defined.
                if (wlex.FlowUrl != null)
                {
                    //If FlowUrl is defined, direct user to the web page to correct the error.
                    throw new ApplicationException(wlex.ErrorString + "Please go to " + wlex.FlowUrl.AbsoluteUri + "to correct the condition that caused the error");
                }
                //If FlowUrl is not defined, simply display the ErrorString.
                throw new Exception(wlex.ErrorString);
            }
        }
    }

}
